package com.liusy.serachengine.parserFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.log4j.Logger;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.POIXMLTextExtractor;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.xmlbeans.XmlException;

public class ParserWord {
	private static Logger log=Logger.getLogger(ParserText.class.getName());
   public static StringBuffer readWord(String path) {
      StringBuffer content = new StringBuffer("");
      File f = new File(path);
      if (!f.exists()) return content;
      try {
         if (path.substring(path.lastIndexOf(".") + 1, path.length()).toLowerCase().equals("docx")) return extractTextFromDOC2007(path);
         FileInputStream fis = new FileInputStream(path);
         HWPFDocument doc = new HWPFDocument(fis);
         Range range = doc.getRange();
         int paragraphCount = range.numParagraphs();// 段落 
         for (int i = 0; i < paragraphCount; i++) {// 遍历段落读取数据 
            org.apache.poi.hwpf.usermodel.Paragraph pp = range.getParagraph(i);
            content.append(pp.text());
         }
         fis.close();
      }
      catch (Exception e) {
    	  log.error("parser Word error:"+path,e);
         System.out.println("提取文件" + path + "的文本内容出错！，附件索引未建成功！");
      }
      return content;
   }

   public static StringBuffer extractTextFromDOC2007(String fileName) throws IOException, OpenXML4JException, XmlException {
      StringBuffer content = new StringBuffer("");// 文档内容 
      OPCPackage opcPackage = POIXMLDocument.openPackage(fileName);
      POIXMLTextExtractor ex = new XWPFWordExtractor(opcPackage);
      return content.append(ex.getText());
   }

}
